package com.share.common.utils;

import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 编码工具类 实现aes加密、解密
 */
@SuppressWarnings("restriction")
public class AESUtil {
    public static final String IMAGE_CODE_KEY = "13223wrwe4345678";//图片验证码的密钥
    /**
     * 密钥长度必须是16
     */
    private static final String defaultKey = "13223wrwe4345678";

    /**
     * 算法
     */
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    //生成key
    public static String genKey(Integer size) {
        if (size == null) {
            size = 64; //是指bit位
        }
        try {
            KeyGenerator kg = KeyGenerator.getInstance("AES");
            kg.init(size);//要生成多少位，只需要修改这里即可128, 192或256
            SecretKey sk = kg.generateKey();
            byte[] b = sk.getEncoded();
            String s = HexUtil.byte2hex(b);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * aes解密
     *
     * @param encrypt 内容
     * @return
     * @throws Exception
     */
    public static String decryptByDefaultKey(String encrypt) throws Exception {
        return decrypt(encrypt, defaultKey);
    }

    /*默认-解密并校验*/
    public static boolean checkDecryptByDefaultKey(String encryptStr, String expectStr) throws Exception {
        String tmp = decryptByDefaultKey(encryptStr);
        if (tmp.equals(expectStr)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * aes加密
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String encryptByDefaultKey(String content) throws Exception {
        return encrypt(content, defaultKey);
    }


    private static String base64Encode(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * base 64 decode
     *
     * @param base64Code 待解码的base 64 code
     * @return 解码后的byte[]
     * @throws Exception
     */
    private static byte[] base64Decode(String base64Code) {
        return StringUtils.isEmpty(base64Code) ? null : Base64.getDecoder().decode(base64Code);
    }

    /**
     * AES加密
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    private static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        byte[] bytes = content.getBytes("utf-8");
        return cipher(bytes, encryptKey, Cipher.ENCRYPT_MODE);
    }

    /**
     * AES加密为base 64 code
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    private static byte[] cipher(byte[] src, String key, int model) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(model, new SecretKeySpec(key.getBytes(), "AES"));
        byte[] result = cipher.doFinal(src);
        return result;
    }

    /**
     * @param src  原始字符串
     * @param key  key
     * @param model 加密或者解密
     * @param ivStr  iv字符串
     * @return
     * @throws Exception
     */
    private static byte[] cipher(byte[] src, String key, int model, String ivStr) throws Exception {
        IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes(StandardCharsets.UTF_8));
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(model, new SecretKeySpec(key.getBytes(), "AES"), iv);
        byte[] result = cipher.doFinal(src);
        return result;
    }

    /**
     * AES解密
     *
     * @param encryptBytes 待解密的byte[]
     * @param decryptKey   解密密钥
     * @return 解密后的String
     * @throws Exception
     */
    private static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
        byte[] decryptBytes = cipher(encryptBytes, decryptKey, Cipher.DECRYPT_MODE);
        return new String(decryptBytes);
    }

    /**
     * 将base 64 code AES解密
     *
     * @param encryptStr 待解密的base 64 code
     * @param decryptKey 解密密钥
     * @return 解密后的string
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    public static void main(String[] arr) throws Exception {
        System.out.println(genKey(64));

        String s = encryptByDefaultKey("fddf1111111rwrqweqweqeqeqeqeqeqeqw1111");
        System.out.println(s);
        String s1 = decryptByDefaultKey(s);
        System.out.println(s1);
    }
}
